package com.xing.binbackend.http.apache;

import com.xing.binbackend.http.HttpClientStrategy;
import com.xing.binbackend.http.RestfulParameters;
import com.xing.binbackend.http.RestfulResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class ApacheHttpClientStrategy implements HttpClientStrategy {
    private final CloseableHttpClient httpClient;

    public ApacheHttpClientStrategy() {
        this.httpClient = HttpClients.createDefault();
    }

    @Override
    public <T> RestfulResponse<T> get(String url, RestfulParameters params, Class<T> responseType) {
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            for (Map.Entry<String, String> entry : params.getParamMap().entrySet()) {
                uriBuilder.addParameter(entry.getKey(), entry.getValue());
            }
            HttpGet request = new HttpGet(uriBuilder.build());

            for (Map.Entry<String, String> entry : params.getHeaderMap().entrySet()) {
                request.setHeader(entry.getKey(), entry.getValue());
            }

            try (CloseableHttpResponse response = httpClient.execute(request)) {
                int statusCode = response.getStatusLine().getStatusCode();
                String responseBody = EntityUtils.toString(response.getEntity());
                T data = responseType.cast(responseBody); // 需要根据实际情况进行反序列化
                return new RestfulResponse<>(statusCode, "Success", data);
            }
        } catch (Exception e) {
            return new RestfulResponse<>(500, e.getMessage(), null);
        }
    }

    @Override
    public <T> RestfulResponse<T> post(String url, RestfulParameters params, Class<T> responseType) {
        // 类似GET方法的实现，使用HttpPost和StringEntity
        return null;
    }

    @Override
    public <T> RestfulResponse<T> put(String url, RestfulParameters params, Class<T> responseType) {
        // 类似GET方法的实现，使用HttpPut和StringEntity
        return null;
    }

    @Override
    public <T> RestfulResponse<T> delete(String url, RestfulParameters params, Class<T> responseType) {
        // 类似GET方法的实现，使用HttpDelete
        return null;
    }
}